package com.xiangban.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiangban.service.ShopService;
import com.xiangban.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;

import static com.xiangban.utils.RedisUtil.fex_shop;


/**
 * @author : manke
 * @Description
 * @Date: 2020/10/31 11:02
 */
@Component
@Slf4j
public class AnnotationParse {
    public final static int flag_no_token = 10001; // 未携带token
    public final static int flag_failed = 10002; // token验证失败
    public final static int flag_no_permission = 10003; //无权限
    public final static int flag_no_voucher = 10004; //未携带有效凭证
    public final static int flag_fail_voucher = 10005; //凭证认证失败
    public final static int pass = 0;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ShopService shopService;

    public Integer Permission(Method method) {
        if (method.isAnnotationPresent(Permission.class)) {
            //验证token
            String token = request.getHeader("token");
            log.info("自定义获取的token：" + token);
            if (token == null || "".equals(token)) {
                log.info("=====未携带token");
                return flag_no_token;
            }
            //获取controller 携带的权限标识
            String permission = method.getAnnotation(Permission.class).permission();
            String userInfo;
            userInfo = redisUtil.get(fex_shop + token);
            if (userInfo == null || "".equals(userInfo)) {
                log.info("=====token验证失败");
                return flag_failed;
            }
            JSONObject jsonObject = JSON.parseObject(userInfo);
            String shopId = jsonObject.get("shopId").toString();
            ArrayList<String> permissionRes = shopService.getPermission(Integer.parseInt(shopId));
            if (!permissionRes.contains(permission)){
                log.info("=====权限验证失败");
                return flag_no_permission;
            }


        }
        return pass;
    }
}
